package m5;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.Scanner;
import java.util.UUID;
import java.util.concurrent.TimeoutException;

public class Consumer {
    public static void main(String[] args) throws IOException, TimeoutException {
        //连接服务器
        ConnectionFactory f = new ConnectionFactory();
        f.setHost("192.168.64.140");
        // 5672 端口，客户端应收发消息的端口
        // 15672 端口。管理控制台界面的访问端口
        f.setPort(5672);
        f.setUsername("admin");
        f.setPassword("admin");
        Connection con = f.newConnection();
        Channel c = con.createChannel();  //通信的通道
        //1.随机队列 2.交换机 3.绑定，设置绑定建
        String queue = UUID.randomUUID().toString();
        c.queueDeclare(queue, false, true, true, null); //非持久，独占，自动删除
        c.exchangeDeclare("topic_logs", BuiltinExchangeType.TOPIC);

        c.queueBind(queue, "topic_logs", "");  //第三个参数对fanout交换机无效

        System.out.println("输入绑定键，用空格隔开：");
        String s = new Scanner(System.in).nextLine().trim();
        String[] a = s.split("\\s+");  //正则表达式 \s 空白字符
        for (String k : a) {
            c.queueBind(queue, "topic_logs", k);
        }

        //回调
        DeliverCallback deliverCallback = (consumerTag, message) -> {
            String key = message.getEnvelope().getRoutingKey();
            String msg = new String(message.getBody());
            System.out.println(key+" -- "+msg);
        };
        CancelCallback cancelCallback = consumerTag -> {};
        //接收消息
        c.basicConsume(queue, true, deliverCallback, cancelCallback);
    }
}